package com.ctp.socket.base;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.ctp.socket.listener.AbstractTraderListener;

public class TcpServer {

	public static void listen(int port, AbstractTraderListener traderListener) {
		ServerSocket server = null;
		try {
			server = new ServerSocket(port);
		} catch (Exception e) {
			return;
		}

		while (true) {
			try {
				Socket client = server.accept();

				InputStreamReader isr = new InputStreamReader(
						client.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(isr);

				OutputStreamWriter osw = new OutputStreamWriter(
						client.getOutputStream(), "UTF-8");
				PrintWriter pw = new PrintWriter(osw);

				String line = br.readLine();
				client.shutdownInput();

				traderListener.processResult(line);

				pw.print("0");
				pw.flush();
				client.shutdownOutput();

				pw.close();
				br.close();
				client.close();
			} catch (Exception e) {
			}
		}
	}

}
